<template>
  <UserLayout :active-index="'2'" :active-menu="'landlord-center'">
    <div class="agent-applications-content">
      <div class="agent-applications-header">
        <el-button type="primary" @click="goBack" class="back-btn">
          <el-icon><ArrowLeft /></el-icon>
          返回房东中心
        </el-button>
        <h2>中介代理申请</h2>
        <p>处理中介提交的房源代理申请</p>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- 代理申请 -->
        <el-tab-pane label="代理申请" name="applications">
          <!-- 筛选条件 -->
          <div class="filter-section">
            <el-form :inline="true" :model="filterForm" class="filter-form">
              <el-form-item label="状态">
                <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="已通过" value="approved" />
                  <el-option label="已拒绝" value="rejected" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="filterApplications">筛选</el-button>
                <el-button @click="resetFilter">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 申请列表 -->
          <div class="applications-list">
            <el-table :data="applications" style="width: 100%" stripe>
              <el-table-column prop="id" label="申请ID" width="100"></el-table-column>
              <el-table-column prop="houseInfo" label="房源信息" width="250"></el-table-column>
              <el-table-column prop="agent" label="中介" width="120"></el-table-column>
              <el-table-column prop="applyTime" label="申请时间" width="180"></el-table-column>
              <el-table-column prop="contactPhone" label="联系电话" width="150"></el-table-column>
              <el-table-column prop="status" label="状态" width="120">
                <template #default="scope">
                  <el-tag
                      :type="scope.row.status === 'pending' ? 'warning' :
                           scope.row.status === 'approved' ? 'success' :
                           scope.row.status === 'rejected' ? 'danger' : 'info'">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250">
                <template #default="scope">
                  <el-button size="small" type="primary" @click="viewApplication(scope.row)">查看详情</el-button>
                  <el-button
                      v-if="scope.row.status === 'pending'"
                      size="small"
                      type="success"
                      @click="approveApplication(scope.row)"
                  >
                    通过
                  </el-button>
                  <el-button
                      v-if="scope.row.status === 'pending'"
                      size="small"
                      type="danger"
                      @click="rejectApplication(scope.row)"
                  >
                    拒绝
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 取消申请 -->
        <el-tab-pane label="取消申请" name="cancellations">
          <!-- 筛选条件 -->
          <div class="filter-section">
            <el-form :inline="true" :model="cancelFilterForm" class="filter-form">
              <el-form-item label="状态">
                <el-select v-model="cancelFilterForm.status" placeholder="请选择状态" clearable>
                  <el-option label="全部" value="" />
                  <el-option label="待审核" value="pending" />
                  <el-option label="已同意" value="approved" />
                  <el-option label="已拒绝" value="rejected" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="filterCancellations">筛选</el-button>
                <el-button @click="resetCancelFilter">重置</el-button>
              </el-form-item>
            </el-form>
          </div>

          <!-- 取消申请列表 -->
          <div class="applications-list">
            <el-table :data="cancelRequests" style="width: 100%" stripe>
              <el-table-column prop="id" label="申请ID" width="100"></el-table-column>
              <el-table-column prop="houseInfo" label="房源信息" width="250"></el-table-column>
              <el-table-column prop="agent" label="中介" width="120"></el-table-column>
              <el-table-column prop="applyTime" label="申请时间" width="180"></el-table-column>
              <el-table-column prop="reason" label="取消原因" width="200"></el-table-column>
              <el-table-column prop="status" label="状态" width="120">
                <template #default="scope">
                  <el-tag
                      :type="scope.row.status === 'pending' ? 'warning' :
                           scope.row.status === 'approved' ? 'success' :
                           scope.row.status === 'rejected' ? 'danger' : 'info'">
                    {{ getCancelStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="250">
                <template #default="scope">
                  <el-button size="small" type="primary" @click="viewCancelRequest(scope.row)">查看详情</el-button>
                  <el-button
                      v-if="scope.row.status === 'pending'"
                      size="small"
                      type="success"
                      @click="approveCancelRequest(scope.row)"
                  >
                    同意
                  </el-button>
                  <el-button
                      v-if="scope.row.status === 'pending'"
                      size="small"
                      type="danger"
                      @click="rejectCancelRequest(scope.row)"
                  >
                    拒绝
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 申请详情对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="currentApplication?.status === 'pending' ? '处理申请' : '申请详情'"
        width="600px"
        :before-close="handleClose"
    >
      <div class="application-detail" v-if="currentApplication">
        <el-form :model="currentApplication" label-width="100px">
          <el-form-item label="申请ID：">
            <span>{{ currentApplication.id }}</span>
          </el-form-item>
          <el-form-item label="房源信息：">
            <span>{{ currentApplication.houseInfo }}</span>
          </el-form-item>
          <el-form-item label="申请时间：">
            <span>{{ currentApplication.applyTime }}</span>
          </el-form-item>
          <el-form-item label="联系电话：">
            <span>{{ currentApplication.contactPhone }}</span>
          </el-form-item>
          <el-form-item label="微信号：">
            <span>{{ currentApplication.wechat || '未提供' }}</span>
          </el-form-item>
          <el-form-item label="中介：">
            <span>{{ currentApplication.agent }}</span>
          </el-form-item>
          <el-form-item label="状态：">
            <el-tag
                :type="currentApplication.status === 'pending' ? 'warning' :
                     currentApplication.status === 'approved' ? 'success' :
                     currentApplication.status === 'rejected' ? 'danger' : 'info'">
              {{ getStatusText(currentApplication.status) }}
            </el-tag>
          </el-form-item>
          <el-form-item label="申请理由：">
            <span>{{ currentApplication.reason }}</span>
          </el-form-item>

          <!-- 处理表单（仅在待审核状态下显示） -->
          <template v-if="currentApplication.status === 'pending'">
            <el-form-item label="处理结果：">
              <el-radio-group v-model="handleResult">
                <el-radio label="approved">通过申请</el-radio>
                <el-radio label="rejected">拒绝申请</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="handleResult === 'rejected'" label="拒绝原因：" prop="rejectReason">
              <el-input
                  v-model="rejectReason"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入拒绝原因"
              />
            </el-form-item>
          </template>

          <el-form-item v-if="currentApplication.rejectReason" label="拒绝原因：">
            <span>{{ currentApplication.rejectReason }}</span>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button
              v-if="currentApplication?.status === 'pending'"
              type="primary"
              @click="handleApplication"
          >
            提交处理结果
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 取消申请详情对话框 -->
    <el-dialog
        v-model="cancelDialogVisible"
        :title="currentCancelRequest?.status === 'pending' ? '处理取消申请' : '取消申请详情'"
        width="600px"
        :before-close="() => cancelDialogVisible = false"
    >
      <div class="application-detail" v-if="currentCancelRequest">
        <el-form :model="currentCancelRequest" label-width="100px">
          <el-form-item label="申请ID：">
            <span>{{ currentCancelRequest.id }}</span>
          </el-form-item>
          <el-form-item label="房源信息：">
            <span>{{ currentCancelRequest.houseInfo }}</span>
          </el-form-item>
          <el-form-item label="申请时间：">
            <span>{{ currentCancelRequest.applyTime }}</span>
          </el-form-item>
          <el-form-item label="中介：">
            <span>{{ currentCancelRequest.agent }}</span>
          </el-form-item>
          <el-form-item label="状态：">
            <el-tag
                :type="currentCancelRequest.status === 'pending' ? 'warning' :
                     currentCancelRequest.status === 'approved' ? 'success' :
                     currentCancelRequest.status === 'rejected' ? 'danger' : 'info'">
              {{ getCancelStatusText(currentCancelRequest.status) }}
            </el-tag>
          </el-form-item>
          <el-form-item label="取消原因：">
            <span>{{ currentCancelRequest.reason }}</span>
          </el-form-item>

          <!-- 处理表单（仅在待审核状态下显示） -->
          <template v-if="currentCancelRequest.status === 'pending'">
            <el-form-item label="处理结果：">
              <el-radio-group v-model="cancelHandleResult">
                <el-radio label="approved">同意取消</el-radio>
                <el-radio label="rejected">拒绝取消</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="cancelHandleResult === 'rejected'" label="拒绝原因：" prop="cancelRejectReason">
              <el-input
                  v-model="cancelRejectReason"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入拒绝原因"
              />
            </el-form-item>
          </template>

          <el-form-item v-if="currentCancelRequest.rejectReason" label="拒绝原因：">
            <span>{{ currentCancelRequest.rejectReason }}</span>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">关闭</el-button>
          <el-button
              v-if="currentCancelRequest?.status === 'pending'"
              type="primary"
              @click="handleCancelRequest"
          >
            提交处理结果
          </el-button>
        </span>
      </template>
    </el-dialog>
  </UserLayout>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import { ArrowLeft } from '@element-plus/icons-vue'

const router = useRouter()

// 返回房东中心
const goBack = () => {
  router.push('/rental/landlord')
}
// 标签页
const activeTab = ref('applications')

// 代理申请数据
const dialogVisible = ref(false)
const currentApplication = ref(null)
const handleResult = ref('approved')
const rejectReason = ref('')

// 取消申请数据
const cancelDialogVisible = ref(false)
const currentCancelRequest = ref(null)
const cancelHandleResult = ref('approved')
const cancelRejectReason = ref('')

// 筛选表单
const filterForm = reactive({
  status: ''
})

const cancelFilterForm = reactive({
  status: ''
})

// 申请数据
const applications = ref([
  {
    id: 5001,
    houseInfo: '北京市朝阳区CBD精致一居室',
    applyTime: '2025-08-01 10:00:00',
    contactPhone: '13800138000',
    wechat: 'zhangsan123',
    status: 'pending',
    agent: '张三中介',
    reason: '本人从事房产中介工作多年，有丰富的客户资源，能够快速找到合适的租客',
    rejectReason: ''
  },
  {
    id: 5002,
    houseInfo: '上海市浦东新区豪华两居室',
    applyTime: '2025-08-02 14:30:00',
    contactPhone: '13900139000',
    wechat: 'lisi456',
    status: 'approved',
    agent: '李四中介',
    reason: '对该区域非常熟悉，有大量潜在客户，能保证房屋快速出租',
    rejectReason: ''
  },
  {
    id: 5003,
    houseInfo: '广州市天河区舒适三居室',
    applyTime: '2025-08-03 09:00:00',
    contactPhone: '13700137000',
    wechat: 'wangwu789',
    status: 'rejected',
    agent: '王五中介',
    reason: '拥有专业的营销团队，能为您的房屋提供最好的推广服务',
    rejectReason: '已有其他中介代理'
  },
  {
    id: 5004,
    houseInfo: '深圳市南山区现代化loft公寓',
    applyTime: '2025-08-04 16:00:00',
    contactPhone: '13600136000',
    wechat: 'zhaoliu111',
    status: 'pending',
    agent: '赵六中介',
    reason: '对该房源所在区域非常了解，有大量客户资源，能快速出租',
    rejectReason: ''
  }
])

// 取消申请数据
const cancelRequests = ref([
  {
    id: 'CR001',
    houseInfo: '深圳市南山区现代化loft公寓',
    applyTime: '2025-08-05 14:30:00',
    agent: '李四中介',
    reason: '房东要求自己管理',
    status: 'pending',
    rejectReason: ''
  },
  {
    id: 'CR002',
    houseInfo: '北京市朝阳区CBD精致一居室',
    applyTime: '2025-08-04 10:15:00',
    agent: '张三中介',
    reason: '找到更好的代理机会',
    status: 'approved',
    rejectReason: ''
  },
  {
    id: 'CR003',
    houseInfo: '上海市浦东新区豪华两居室',
    applyTime: '2025-08-03 16:45:00',
    agent: '王五中介',
    reason: '个人原因无法继续代理',
    status: 'rejected',
    rejectReason: '当前推广效果良好，暂不同意取消'
  }
])

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending': return '待审核'
    case 'approved': return '已通过'
    case 'rejected': return '已拒绝'
    default: return '未知'
  }
}

// 查看申请详情
const viewApplication = (application) => {
  currentApplication.value = application
  handleResult.value = application.status === 'pending' ? 'approved' : application.status
  rejectReason.value = application.rejectReason || ''
  dialogVisible.value = true
}

// 通过申请
const approveApplication = (application) => {
  ElMessageBox.confirm(
      `确定要通过 ${application.agent} 的代理申请吗？`,
      '通过申请',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    application.status = 'approved'
    ElMessage.success('申请已通过')
  })
}

// 拒绝申请
const rejectApplication = (application) => {
  ElMessageBox.prompt('请输入拒绝原因', '拒绝申请', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '拒绝原因不能为空'
  }).then(({ value }) => {
    application.status = 'rejected'
    application.rejectReason = value
    ElMessage.success('申请已拒绝')
  })
}

// 处理申请
const handleApplication = () => {
  if (handleResult.value === 'rejected' && !rejectReason.value.trim()) {
    ElMessage.error('请输入拒绝原因')
    return
  }

  if (handleResult.value === 'rejected') {
    currentApplication.value.status = 'rejected'
    currentApplication.value.rejectReason = rejectReason.value
  } else {
    currentApplication.value.status = 'approved'
  }

  ElMessage.success('处理成功')
  dialogVisible.value = false
}

// 关闭对话框前的处理
const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭详情页面吗？')
      .then(() => {
        done()
      })
      .catch(() => {
        // 取消关闭
      })
}

// 筛选申请
const filterApplications = () => {
  ElMessage.info('正在筛选申请')
}

// 重置筛选
const resetFilter = () => {
  filterForm.status = ''
  ElMessage.info('已重置筛选条件')
}

// 标签页切换
const handleTabChange = (tabName) => {
  console.log('切换到标签页:', tabName)
}

// 取消申请相关方法
const getCancelStatusText = (status) => {
  switch (status) {
    case 'pending': return '待审核'
    case 'approved': return '已同意'
    case 'rejected': return '已拒绝'
    default: return '未知'
  }
}

// 查看取消申请详情
const viewCancelRequest = (request) => {
  currentCancelRequest.value = request
  cancelHandleResult.value = request.status === 'pending' ? 'approved' : request.status
  cancelRejectReason.value = request.rejectReason || ''
  cancelDialogVisible.value = true
}

// 同意取消申请
const approveCancelRequest = (request) => {
  ElMessageBox.confirm(
      `确定要同意 ${request.agent} 的取消申请吗？`,
      '同意取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    request.status = 'approved'
    ElMessage.success('已同意取消申请')
  })
}

// 拒绝取消申请
const rejectCancelRequest = (request) => {
  ElMessageBox.prompt('请输入拒绝原因', '拒绝取消', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '拒绝原因不能为空'
  }).then(({ value }) => {
    request.status = 'rejected'
    request.rejectReason = value
    ElMessage.success('已拒绝取消申请')
  })
}

// 处理取消申请
const handleCancelRequest = () => {
  if (cancelHandleResult.value === 'rejected' && !cancelRejectReason.value.trim()) {
    ElMessage.error('请输入拒绝原因')
    return
  }

  if (cancelHandleResult.value === 'rejected') {
    currentCancelRequest.value.status = 'rejected'
    currentCancelRequest.value.rejectReason = cancelRejectReason.value
    ElMessage.success('已拒绝取消申请')
  } else {
    currentCancelRequest.value.status = 'approved'
    ElMessage.success('已同意取消申请')
  }

  cancelDialogVisible.value = false
}

// 筛选取消申请
const filterCancellations = () => {
  ElMessage.info('正在筛选取消申请')
}

// 重置取消申请筛选
const resetCancelFilter = () => {
  cancelFilterForm.status = ''
  ElMessage.info('已重置筛选条件')
}

</script>

<style scoped>
.agent-applications-content {
  padding: 20px;
}

.agent-applications-header {
  text-align: center;
  margin-bottom: 30px;
  position: relative;
}

.agent-applications-header h2 {
  color: #2c3e50;
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 10px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.agent-applications-header p {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

.back-btn {
  position: absolute;
  top: 0;
  left: 0;
}

.filter-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.applications-list {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.application-detail {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .agent-applications-content {
    padding: 15px;
  }

  .agent-applications-header h2 {
    font-size: 24px;
  }

  .back-btn {
    position: static;
    margin-bottom: 20px;
  }
}
</style>
